import { useUserStore } from "@/store/user";

const baseURL = "http://campus.kangcpu.top/index";

const request = (options) => {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore();
    const token = userStore.token;

    // 合并请求头
    const header = {
      ...options.header,
    };

    // 如果有token，添加到请求头
    if (token) {
      header["Authorization"] = token;
    }

    uni.request({
      url: baseURL + options.url,
      method: options.method || "GET",
      data: options.data,
      header: header,
      success: (res) => {
        // 请求成功

        if (res.data.code === 200) {
          resolve(res.data);
        }
        // token失效
        else if (res.data.code === 501) {
          userStore.clearUserInfo();
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/login/login",
            });
          }, 1000);
          uni.navigateTo({
            url: "/pages/login/login",
          });
          reject(res);
        }
        // 其他错误
        else {
          uni.showToast({
            title: res.data.message || "请求失败",
            icon: "none",
          });
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: "网络请求失败",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

export default request;
